package com.dhecp.project.flowable.cmd;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.compatibility.Flowable5CompatibilityHandler;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.Flowable5Util;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

/**
 * @ClassName AddTaskCommentCmd
 * @Description TODO
 * @Author alula
 * @Date 2022-01-27 15:13
 */
public class AddTaskCommentCmd implements Command<Comment> {

    protected String taskId;
    protected String processInstanceId;
    protected String type;
    protected String message;

    public AddTaskCommentCmd(String taskId, String processInstanceId, String message) {
        this.taskId = taskId;
        this.processInstanceId = processInstanceId;
        this.message = message;
    }

    public AddTaskCommentCmd(String taskId, String processInstanceId, String type, String message) {
        this.taskId = taskId;
        this.processInstanceId = processInstanceId;
        this.type = type;
        this.message = message;
    }

    @Override
    public Comment execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        TaskEntity task = null;
        if (this.taskId != null) {
            task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(this.taskId);
            if (task == null) {
                throw new FlowableObjectNotFoundException("Cannot find task with id " + this.taskId, Task.class);
            }

            if (task.isSuspended()) {
                throw new FlowableException(this.getSuspendedTaskException());
            }
        }

        ExecutionEntity execution = null;
        if (this.processInstanceId != null) {
            execution = (ExecutionEntity)processEngineConfiguration.getExecutionEntityManager().findById(this.processInstanceId);
            if (execution == null) {
                throw new FlowableObjectNotFoundException("execution " + this.processInstanceId + " doesn't exist", Execution.class);
            }

            if (execution.isSuspended()) {
                throw new FlowableException(this.getSuspendedExceptionMessage());
            }
        }

        String processDefinitionId = null;
        if (execution != null) {
            processDefinitionId = execution.getProcessDefinitionId();
        } else if (task != null) {
            processDefinitionId = task.getProcessDefinitionId();
        }

        if (processDefinitionId != null && Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, processDefinitionId)) {
            Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
            return compatibilityHandler.addComment(this.taskId, this.processInstanceId, this.type, this.message);
        } else {
            String userId = Authentication.getAuthenticatedUserId();
            CommentEntity comment = (CommentEntity)processEngineConfiguration.getCommentEntityManager().create();
            comment.setUserId(userId);
            comment.setType(this.type == null ? "comment" : this.type);
            comment.setTime(processEngineConfiguration.getClock().getCurrentTime());
            comment.setTaskId(this.taskId);
            comment.setProcessInstanceId(this.processInstanceId);
            comment.setAction("AddComment");
            String eventMessage = this.message.replaceAll("\\s+", " ");
            if (eventMessage.length() > 993) {
                eventMessage = eventMessage.substring(0, 990) + "...";
            }
            comment.setMessage(eventMessage);
            comment.setFullMessage(this.message);
            processEngineConfiguration.getCommentEntityManager().insert(comment);
            return comment;
        }
    }

    protected String getSuspendedTaskException() {
        return "Cannot add a comment to a suspended task";
    }

    protected String getSuspendedExceptionMessage() {
        return "Cannot add a comment to a suspended execution";
    }
}
